package com.wisdytech.linkdcs.equipLifeCycle.check.service.impl;

import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import com.wisdytech.linkdcs.equipLifeCycle.check.dao.ICheckModelItemDao;
import com.wisdytech.linkdcs.equipLifeCycle.check.model.CheckModelItem;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.event.EventListener;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import com.alibaba.fastjson.JSON;
import com.baomidou.mybatisplus.mapper.EntityWrapper;
import com.github.pagehelper.PageInfo;
import com.wisdytech.common.bean.Filter;
import com.wisdytech.common.bean.event.EquipEvent;
import com.wisdytech.common.bean.event.EquipEvent2;
import com.wisdytech.common.constants.CommonConstants;
import com.wisdytech.common.enums.ActionType;
import com.wisdytech.common.exception.ServiceException;
import com.wisdytech.common.handler.BaseService;
import com.wisdytech.common.utils.BaseUtil;
import com.wisdytech.linkdcs.equipLifeCycle.check.dao.ICheckDao;
import com.wisdytech.linkdcs.equipLifeCycle.check.dto.CheckSearchDto;
import com.wisdytech.linkdcs.equipLifeCycle.check.model.Check;
import com.wisdytech.linkdcs.equipLifeCycle.check.service.ICheckService;
import com.wisdytech.linkdcs.equipLifeCycle.check.vo.CheckVo;
import com.wisdytech.linkdcs.equipment.dao.IEqEquipmentDao;
import com.wisdytech.linkdcs.equipment.model.Equipment;

/**
 * <p>
 *  服务实现类
 * </p>
 *
 * @author dailibo
 * @since 2018-06-05
 */
@Service
@Transactional
public class CheckServiceImpl extends BaseService<ICheckDao, Check> implements ICheckService {

	private Logger logger =LoggerFactory.getLogger(getClass());
	
	@Autowired
	private ICheckDao iCheckDao;
	
	@Autowired
	private IEqEquipmentDao iEqEquipmentDao;
    @Autowired
    private ICheckModelItemDao iCheckModelItemDao;

	@Override
	public boolean addCheckRecord(String eqCode,String createUser) {
		logger.info("增加设备点检记录");

		//判断是否存在记录
		EntityWrapper<Check> ew =new EntityWrapper<>();
		if(iCheckDao.selectCount(ew.eq("EQUIP_CODE", eqCode).eq("DEL_FLAG", CommonConstants.DEL_FLAG))<=0){
			//新增一条记录
			Check check =new Check();
			check.setPkId(BaseUtil.getUUID());
			check.setEquipCode(eqCode);
			check.setCreateUser(createUser);
			check.setCreateDate(new Date());
			check.setUpdateDate(new Date());
			check.setDelFlag(CommonConstants.DEL_FLAG);
			return check.insert();
		}else {
			//更新记录
			EntityWrapper<Check> ewUpdate =new EntityWrapper<>();
			Check check =new Check();
			check.setUpdateUser(createUser);
			check.setUpdateDate(new Date());
			check.setDelFlag(CommonConstants.DEL_FLAG);
			iCheckDao.update(check, ewUpdate.eq("EQUIP_CODE", eqCode));
		}


		return true;
	}

	@Override
	public boolean addCheckRecordByModel(String modelCode,String createUser) {
		
//		Map<String,Object> queryMap=new HashMap<>();
//		queryMap.put("modelCode", modelCode);
		
		EntityWrapper<Equipment> ew = new EntityWrapper<>();
		ew.eq("model_code", modelCode);
		List<Equipment> equipments =
				iEqEquipmentDao.selectList(ew);
		
		for(Equipment equipment : equipments){
			//更新单个点检列表失败
			if(!addCheckRecord(equipment.getEquipCode(),createUser)) {
				throw new ServiceException("新增点检列表失败");
			}
		}
		
		return  true;
	}

	@Override
	public boolean delCheckRecord(String eqCode,String delUser) {
		//更新记录
		EntityWrapper<Check> ewUpdate =new EntityWrapper<>();
		Check check =new Check();
		check.setUpdateUser(delUser);
		check.setUpdateDate(new Date());
		check.setDelFlag(CommonConstants.DEL_FLAG_TRUE);
		return iCheckDao.update(check, ewUpdate.eq("EQUIP_CODE", eqCode))>=0?true:false;
	}

	@Override
	public boolean delCheckRecordByModel(String modelCode,String createUser) {
        EntityWrapper<Equipment> ew = new EntityWrapper();
        ew.eq("MODEL_CODE",modelCode);
		ew.eq("DEL_FLAG",CommonConstants.DEL_FLAG);
        List<Equipment> equipments =
        iEqEquipmentDao.selectList(ew);
		for(Equipment equipment : equipments){
			//更新单个点检列表失败
			delCheckRecord(equipment.getEquipCode(),createUser);
		}
		
		return true;
	}

	@Override
	public PageInfo<CheckVo> listEquipChecks(Filter filter, CheckSearchDto dto) {
		
		List<CheckVo>  result=
				this.beforeList(ICheckDao.class, filter).selectCheckRecord(dto);
		
		return new PageInfo<CheckVo>(result);
	}
	
	
	//设备增删改查事件，同步处理点检管理
	@EventListener
	protected void 	equipEventListener(EquipEvent equipEvent) {
		logger.warn("设备增删改，同步推送至点检管理   "+JSON.toJSONString(equipEvent));
		
		switch (equipEvent.getType().getCode()) {
		case 1://新增
			for(String equipCode :equipEvent.getEquipCode()) {
			    //获取设备型号
                Equipment equipment = new Equipment();
                equipment.setEquipCode(equipCode);
                equipment.setDelFlag(CommonConstants.DEL_FLAG);
                Equipment e = iEqEquipmentDao.selectOne(equipment);
                EntityWrapper<CheckModelItem> ew = new EntityWrapper();
                ew.eq("MODEL_CODE",e.getModelCode());
                ew.eq("DEL_FLAG",CommonConstants.DEL_FLAG);
                List<CheckModelItem> list = iCheckModelItemDao.selectList(ew);
                if(!list.isEmpty()){
                    addCheckRecord(equipCode, equipEvent.getDealUser());
                }
			}
			break;
		case 3://删除
			for(String equipCode :equipEvent.getEquipCode()) {
				delCheckRecord(equipCode, equipEvent.getDealUser());
			}
			break;
		default:
			logger.warn("设备修改，同步推送至点检");
			break;
		}
	}

}
